package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.wemedia.IWeUserClient;
import com.heima.model.admin.dtos.AuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.service.ApUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author fly
 */
@Slf4j
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Override
    public PageResponseResult findList(AuthDto authDto) {
        if (authDto == null) {
            return (PageResponseResult) PageResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        IPage page = new Page(authDto.getPage(), authDto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (authDto.getStatus() != null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus, authDto.getStatus());
        }
        lambdaQueryWrapper.orderByDesc(ApUserRealname::getCreatedTime);
        page = page(page, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(authDto.getPage(), authDto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult authFail(AuthDto authDto) {
        ApUserRealname userRealname = getById(authDto.getId());
        userRealname.setReason(authDto.getMsg());
        userRealname.setStatus((short) 2);
        updateById(userRealname);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private ApUserService apUserService;
    @Autowired
    private IWeUserClient iWeUserClient;

    @Override
    public ResponseResult authPass(AuthDto authDto) {
        ApUserRealname userRealname = getById(authDto.getId());
        userRealname.setStatus((short) 9);
        updateById(userRealname);
        ApUser apUser = apUserService.getById(userRealname.getUserId());
        WmUser wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        return iWeUserClient.authPass(wmUser);
    }
}
